const express = require("express");
const { upload } = require('@middleware/upload');
const async = require('async');
const router = express.Router();

router.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "content-type");
  res.header("Access-Control-Allow-Methods", "DELETE, PUT, POST, GET, OPTIONS");
  if (req.method.toLowerCase() == "options") {
    res.send(200);
  } else {
    next();
  }
});

// Vue Demo 接口
router.use("/vue/v1", require("./vue/index"));

// 微信小程序接口
// router.use("/wechat/v1", require("./wechat/index"));

// 企业微信小程序接口
// router.use("/qy/v1", require("./qy/index"));

// router.get("/data", () => {
//   let params = req.query ? req.query : {};
//   console.log("params", params);
//   fetchHtmlInfo(params, function (data) {
//     res.json({
//       ok: true,
//       name: "test",
//       data: data,
//     });
//   });
// });

// 爬虫 —— cheerio 或 puppeteer
// puppeteer 能获取 js 动态生成的元素；还能获取 iframe
// html文档编码问题，使用cheerio模块读取能解析的默认是gbk编码，而有些文档是gb2312编码，这里如果用cheerio.load(html)就解析不出来，我们需要用到另一个东西chrset  和 superagent 先安装 npm install 模块名  ；
// const charset = require("superagent-charset");
// const agent = require("superagent");
// charset(agent);
// function cheerioData(url) {
//   let html = '';
//   let resStr = '';
//   agent.get(url).charset('gbk').end(function (err,res) {
//       if(err){
//           console.log('读取数据错误',err);
//       }else{
//           html =res.text;
//           let $ = cheerio.load(html);
//           let content =$('.kjxq_box02');
//           let qs = $('.cfont2 strong').text();
//           console.log(qs);
//       }
//   })
// }



async function dddddd(params) {
  let url = "https://music.163.com/#/song?id=1338695683";
  let browser = await puppeteer.launch();
  let page = await browser.newPage();

  await page.goto(url);
  // 获取歌单的iframe
  let iframe = await page.frames().find((f) => f.name() === "contentFrame");
  let data = await iframe.evaluate(function () {
    let list_n = document.querySelectorAll(".cmmts .itm .cnt a");
    let list_d = document.querySelectorAll(".cmmts .itm .cnt");
    let list_i = document.querySelectorAll(".cmmts .itm .head img");
    let data = [];
    for (let i = 0; i < list_n.length; i++) {
      let name = list_n[i].innerText;
      let icon = list_i[i].getAttribute("src");
      data.push({
        icon: icon.replace(/\/\r\n/g, "").trim(),
        name: name.trim(),
        desc: list_d[i].innerText
          .replace(name + "：", " ")
          .replace(/\/\r\n/g, "")
          .trim(),
      });
    }
    return data;
  });
  console.log("data", data);
}

router.use((req, res, next) => {
  responseData = {
    code: 0,
    message: "",
  };
  next();
});
router.post("/test", (req, res) => {
  console.log(req, res);
  const params = req.query;
  res.json({
    code: 200,
    msg: "成功",
  });
  responseData.data = shop;
  res.json(responseData);
});

router.post("/upload", upload, (req, res) => {
  console.log(res);
  const { file } = req.body;
  // const base64 = file.replace(/^data:image\/\w+;base64,/, "");
  // const bitmap = new Buffer.from(base64, 'base64');
  // fs.writeFile(path.resolve(__dirname, "../../public/upload", 'image.png'), bitmap, (err) => {
  //   if(err){
  //     res.send(err);
  //   }else{
      res.send({
        code: 200,
        msg:"保存成功！",
      });
    // }
  // });
});



// 批量下载图片
// 解决方案一: 使用async异步批量下载图片
//  async 包，是一个流程控制工具包，提供了直接而强大的异步功能。其提供了大约20个函数，包括常用的 map, reduce, filter, forEach 等，异步流程控制模式包括，串行(series)，并行(parallel)，瀑布(waterfall)等。
// 在Mac上使用的时候,偶尔会出现这样的错误:

// Error: EMFILE, too many open files
// 有可能是因为Mac对并发打开的文件数限制的比较小,一般为256.所以需要修改一下。

// 在命令行执行:

// echokern.maxfiles=65536 | sudo tee-a/etc/sysctl.conf
// echokern.maxfilesperproc=65536 | sudo tee-a/etc/sysctl.conf
// sudo sysctl -w kern.maxfiles=65536
// sudo sysctl -w kern.maxfilesperproc=65536
// ulimit-n 65536 65536
// 然后可以在你的.bashrc文件中加入一行:

// ulimit -n 65536 65536
function downloadImage (src, dest, callback) {
  request.head(src, function(err, res, body){
 // console.log('content-type:', res.headers['content-type']);
 // console.log('content-length:', res.headers['content-length']);
 if(src) {
  request(src).pipe(fs.createWriteStream(dest)).on('close',function(){
  callback(null, dest);
  });
  }
  });
 };
 
router.get('/', (req, res) => {
  const imageLinks = [
    'http://static.wooyun.org//drops/20160315/2016031513484536696130.png',
    'http://static.wooyun.org//drops/20160315/2016031513484767273224.png',
    'http://static.wooyun.org//drops/20160315/2016031513485057874324.png',
    'http://static.wooyun.org//drops/20160315/2016031513485211060411.png',
    'http://static.wooyun.org//drops/20160315/201603151348542560759.png',
    'http://static.wooyun.org//drops/20160315/201603151348563741969.png',
    'http://static.wooyun.org//drops/20160315/201603151348582588879.png',
    'http://static.wooyun.org//drops/20160315/201603151349001461288.png',
    'http://static.wooyun.org//drops/20160315/201603151349032455899.png',
    'http://static.wooyun.org//drops/20150714/2015071404144944570.png',
    'http://static.wooyun.org//drops/20150714/2015071404144966345.png',
    'http://static.wooyun.org//drops/20150714/2015071404144915704.png',
    'http://static.wooyun.org//drops/20150714/2015071404144980399.png',
    'http://static.wooyun.org//drops/20150714/2015071404144927633.png'
  ];
  async.mapSeries(imageLinks, (item, callback) => {
    setTimeout(() => {
      if(item.indexOf("http://static.wooyun.org") === 0) {
        const destImage = path.resolve("./images/", item.split("/")[item.split("/").length-1]);
        downloadImage(item, destImage, (err, data) => {
          console.log("["+ index++ +"]: "+ data);
     });
     
     }
     callback(null, item);
     }, 100);
     
     
    }, function(err, results){});
})

// 解决方案二: 使用bagpipe批量下载图片
// for(vari =0; i < imageLinks.length; i++) {
//   if(imageLinks[i].indexOf("http://static.wooyun.org") ===0) {
//   vardestImage = path.resolve("./images/", imageLinks[i].split("/")[imageLinks[i].split("/").length-1]);
//    bagpipe.push(downloadImage, imageLinks[i], destImage, function(err, data){
//   console.log("["+ index++ +"]: "+ data);
//    });
//    }
//   }

module.exports = router;
